from datetime import datetime
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import os
import sys
from outlook.email_logic import AuthManager, EmailSender, parse_recipients

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("M365 批量工具")
        self.setGeometry(100, 100, 800, 600)
        self.tabs = QTabWidget()
        self.email_tab = QWidget()
        self.init_email_tab()
        self.tabs.addTab(self.email_tab, "邮件工具")
        self.SharePoint_tab = QWidget()
        self.init_SharePoint_tab()
        self.tabs.addTab(self.SharePoint_tab, "SharePoint工具")
        self.PowerBi_tab = QWidget()
        self.init_PowerBi_tab()
        self.tabs.addTab(self.PowerBi_tab, "PowerBi工具")
        self.setCentralWidget(self.tabs)
        self.auth_manager = None

    def init_email_tab(self):
        layout = QVBoxLayout() # 垂直布局管理器
        auth_layout = QHBoxLayout() # 创建用户认证部分的水平管理器
        count_layout = QHBoxLayout() #创建发送个数的水平管理器
        sender_layout = QHBoxLayout() #创建发件人的水平管理器
        recipient_layout = QHBoxLayout() #创建收件人的水平管理器

        # 创建所有的输入框和 输入框的标题
        self.client_id_input = QLineEdit(placeholderText="Azure中注册的APP ID")
        self.tenant_id_input = QLineEdit(placeholderText="Tenant ID")
        self.login_btn = QPushButton("登录 M365")
        self.count_input = QLineEdit(placeholderText="请输入需要发送邮件的数量（默认1）")
        auth_layout.addWidget(QLabel("Client ID:"))
        auth_layout.addWidget(self.client_id_input)
        auth_layout.addWidget(QLabel("Tenant ID:"))
        auth_layout.addWidget(self.tenant_id_input)
        auth_layout.addWidget(self.login_btn)
        count_layout.addWidget(QLabel("发送数量:"))
        count_layout.addWidget(self.count_input)
        # 将两个水平管理器添加到垂直管理器中
        layout.addLayout(auth_layout)
        layout.addLayout(count_layout)

        # 邮件内容输入部分
        self.sender_email_input = QLineEdit(placeholderText="发件人邮箱")
        sender_layout.addWidget(QLabel("Send from:"))
        sender_layout.addWidget(self.sender_email_input)
        self.subject_input = QLineEdit(placeholderText="请输入subject")
        self.body_edit = QTextEdit()
        self.recipient_input = QLineEdit(placeholderText="手动输入收件人（多个用逗号分隔）")
        self.recipient_file_btn = QPushButton("选择收件人列表")
        self.recipient_file_label = QLabel("未选择文件")
        recipient_layout.addWidget(QLabel("Send to:"))
        recipient_layout.addWidget(self.recipient_input)
        recipient_layout.addWidget(self.recipient_file_btn)
        recipient_layout.addWidget(self.recipient_file_label)
        layout.addLayout(recipient_layout)
        instruction_label = QLabel("说明：<Send to> 和 <选择收件人列表>只能二选一, <选择收件人列表> 一般用于不想手动输入收件人的情况")
        instruction_label.setStyleSheet("color:green;")
        layout.addWidget(instruction_label)
        layout.addWidget(QLabel("subject:"))
        layout.addWidget(self.subject_input)
        layout.addWidget(QLabel("正文:"))
        layout.addWidget(self.body_edit)

        # 附件选择
        file_layout = QHBoxLayout()
        self.attachment_btn = QPushButton("选择附件")
        self.attachment_label = QLabel("未选择附件")
        file_layout.addWidget(self.attachment_btn)
        file_layout.addWidget(self.attachment_label)
        layout.addLayout(file_layout)

        # 操作按钮
        self.send_btn = QPushButton("开始发送")
        btn_layout = QHBoxLayout()
        btn_layout.addWidget(self.send_btn)
        layout.addLayout(btn_layout)

        # 进度与日志
        self.progress_bar = QProgressBar()
        self.log_edit = QTextEdit(readOnly=True)
        layout.addWidget(QLabel("进度:"))
        layout.addWidget(self.progress_bar)
        layout.addWidget(QLabel("日志:"))
        layout.addWidget(self.log_edit)

        # 连接信号与槽函数
        self.recipient_input.textChanged.connect(self.check_recipient_file_btn_state)
        self.recipient_file_btn.clicked.connect(self.check_recipient_input_state)
        self.login_btn.clicked.connect(self.on_login)
        self.send_btn.clicked.connect(self.on_send)

        self.email_tab.setLayout(layout)
    # init_email_tab 保持不变，只列出修改的部分
    def on_login(self):
        client_id = self.client_id_input.text().strip()
        tenant_id = self.tenant_id_input.text().strip()
        if not client_id:
            QMessageBox.warning(self, "输入错误", "client id不能为空")
            return
        if not tenant_id:
            QMessageBox.warning(self, "输入错误", "tenant id不能为空")
            return
        self.auth_manager = AuthManager(client_id, tenant_id)
        if self.auth_manager.login():
            self.log("登录成功")
            self.login_btn.setText("已登录")
            self.login_btn.setDisabled(True)
        else:
            self.log("登录失败，请检查 Client ID 和 Tenant ID")
            QMessageBox.warning(self, "登录失败", "请检查凭据或网络连接")


    def on_send(self):
        pass


    def init_SharePoint_tab(self):
        pass

    def init_PowerBi_tab(self):
        pass

    def log(self, message):
        self.log_edit.append(f"[{datetime.now().strftime('%H:%M:%S')}] {message}")
    # 槽函数
    def check_recipient_file_btn_state(self):
        """手动输入框有内容时，禁用选择收件人列表按钮"""
        if self.recipient_input.text():
            self.recipient_file_btn.setDisabled(True)
        else:
            self.recipient_file_btn.setDisabled(False)

    def check_recipient_input_state(self):
        """当选择收件人文件时，禁用手动输入框"""
        file_path, _ = QFileDialog.getOpenFileName(self, "选择收件人列表", "", "Excel/CSV (*.xlsx *.csv)")
        if file_path:
            self.recipient_file_label.setText(file_path)
            self.recipient_input.setDisabled(True)
        else:
            self.recipient_file_label.setText("未选择文件")  # 清空文件选择显示
            self.recipient_input.setEnabled(True)  # 恢复手动输入框

    # check_recipient_file_btn_state 和 check_recipient_input_state 不变

if __name__ == "__main__":
    # 每一个pyqt程序中都需要有一个QApplication对象，sys.argv是一个命令行参数列表
    app = QApplication(sys.argv)
    # 实例化窗口
    form = MainWindow()
    # 窗口展示
    form.show()
    # 遇到退出情况，终止程序
    sys.exit(app.exec_())
